/** DEFAULTNAMES
 *  OLMAP 方法函数
 *  layer操作方法 
 *  @author Goog2023
 */
import {
	fCommon
} from ".";
import {
	isFun
} from "./fCommon";
import {
	fGetView
} from "./fView";
import constants from "../constants";
import {
	DEFAULTNAMES
} from "../constants"
// 创建Vector图层
function fCreateVectorLayer(configs = {}, callback) {
	/* layer 是 layer的配置项 source 是source的配置项 传入参数应该为{layer:{},source:{}}*/
	const defaultConfigs = {
		layer: new Object(),
		source: new Object()
	};
	const layer = new ol.layer.Vector({
		source: new ol.source.Vector(Object.assign(defaultConfigs.source, configs.source || {})),
		...Object.assign(defaultConfigs.layer, configs.layer || {}),
	});
	return isFun(callback) ? callback(layer) : layer;
}


// 创建WMTS图层
function fCreateWMTSLayer(configs = {}, callback) {
	const defaultConfigs = {
		layer: new Object(),
		source: new Object()
	};
	const layer = new ol.layer.Tile({
		source: new ol.source.WMTS(Object.assign(defaultConfigs.source, configs.source || {})),
		...Object.assign(defaultConfigs.layer, configs.layer || {}),
	});
	return isFun(callback) ? callback(layer) : layer;
}

// 创建天地图WMTS图层
function fCreateTDTWMTSLayer(
	configs = {},
	callback
) {
	const type = configs.type || 'img_c'
	const proj = configs.proj || 'EPSG:4326'
	const tk = configs.tk || 'b3440419e80cf230d76f0c674f867eb3'
	const projection = ol.proj.get(proj);
	const projectionExtent = projection.getExtent();
	const size = ol.extent.getWidth(projectionExtent) / 256;
	const resolutions = new Array(19);
	const matrixIds = new Array(19);
	for (let z = 0; z < 19; ++z) {
		// generate resolutions and matrixIds arrays for this WMTS
		resolutions[z] = size / Math.pow(2, z);
		matrixIds[z] = z;
	}
	const sourceConfig = {
		url: `http://t{0-7}.tianditu.com/${type}/wmts?tk=${tk}`,
		layer: type.substr(0, 3),
		matrixSet: type.substring(4),
		format: 'tiles',
		projection: projection,
		tileGrid: new ol.tilegrid.WMTS({
			origin: ol.extent.getTopLeft(projectionExtent),
			resolutions: resolutions,
			matrixIds: matrixIds
		}),
		style: 'default',
		wrapX: true
	}
	return fCreateWMTSLayer({
		source: sourceConfig,
		layer: {}
	}, callback)
}

// 创建天地图底图
function fCreateTDTBaseMap(configs = {}, isShow = false, baseMapGroupIndex = 0, baseMapGroupName = 'BASEMAP') {
	return fCreateTDTWMTSLayer(configs, (layer) => {
		// layer.setVisible(isShow);
		fSetLayerProps(layer, {
			id: baseMapGroupName + '-' + (configs.type || baseMapGroupIndex),
			group: baseMapGroupName + '-' + baseMapGroupIndex,
			visible: isShow,
			zIndex: -1
		})
		// layer['id'] = 
		// layer['group'] = baseMapGroupName + '-' + baseMapGroupIndex;
		// layer.setZIndex(-1);
		return layer;
	});
}

// 初始化天地图地图(加载)
function fInitTDTBaseMap(proj = 'EPSG:4326', tdtConfig = {}) {
	const config = Object.assign({
		tk: 'b3440419e80cf230d76f0c674f867eb3', // 加载天地图时候的tk
		baseMap: [
			['img_c', 'vic_c'],
			['vec_c', 'cva_c']
		],
		baseMapIndex: 0,
	}, tdtConfig);

	const baseMapLayers = [];
	config.baseMap.forEach((item, index) => {
		if (Array.isArray(item)) {
			item.forEach((items) => {
				baseMapLayers.push(fCreateTDTBaseMap({
					proj,
					type: items,
					tk: config.tk
				}, index == config.baseMapIndex, index));
			})
		} else {
			baseMapLayers.push(fCreateTDTBaseMap({
				proj,
				type: item,
				tk: config.tk
			}, index == config.baseMapIndex, index))
		}
	});
	return baseMapLayers;
}

//获取所有layers
function fGetLayers() {
	try {
		const layers = [];
		this.getLayers().forEach(layer => {
			layers.push(layer);
		})
		return layers;
	} catch (err) {
		console.warn(err);
		return [];
	}
}

//获取过滤后的layers
function fGetFilterLayers(callback = () => true) {
	try {
		const layers = [];
		this.getLayers().forEach(layer => {
			if (fCommon.isFun(callback)) {
				callback(layer) ? layers.push(layer) : '';
			} else {
				layers.push(layer);
			}
		})
		return layers;
	} catch (err) {
		console.warn(err);
		return [];
	}
}

//判断是否为地图 底图
function fIsBaseMap(group = '') {
	return group.indexOf(DEFAULTNAMES.BASEMAPGROUPNAME) != -1
}

//获取所有底图
function fGetBaseMaps() {
	return fGetFilterLayers.call(this, (layer) => {
		return fIsBaseMap(fGetGroupNameByLayer(layer));
	})
}

//切换底图
function fChangeBaseMap(gruopIndex = 0) {
	fGetBaseMaps.call(this).forEach((layer) => {
		//console.log(fGetGroupNameByLayer(layer), DEFAULTNAMES.BASEMAPGROUPNAME + '-' + gruopIndex);
		layer.setVisible(fGetGroupNameByLayer(layer) == DEFAULTNAMES.BASEMAPGROUPNAME + '-' + gruopIndex);
	})
}

// 获取分组名称
function fGetGroupNameByLayer(layer) {
	return fGetLayerProp(layer, 'group') || '';
}
// 获取layer所有项属性值
function fGetLayerProps(layer) {
	try {
		return layer.getProperties();
	} catch (err) {
		return {};
	}
}

// 获取layer某项属性值
function fGetLayerProp(layer, key = 'id') {
	try {
		return fGetLayerProps(layer)[key];
	} catch (err) {
		return null;
	}
}
// 设置layer属性值
function fSetLayerProps(layer, props = {}) {
	try {
		if (layer) {
			layer.setProperties(props);
		}

	} catch (err) {
		console.warn(err);
	}

}
// 通过id获得某个图层
function fGetLayerByID(id = '') {

	return fGetLayer.call(this, 'id', id);
}

function fGetLayer(prop = 'id', val = '') {
	let targetLayer = null;

	fGetLayers.call(this).forEach(layer => {
		if (fGetLayerProp(layer, prop) == val) {
			targetLayer = layer;
		}
	})
	return targetLayer;
}

export {
	fCreateWMTSLayer,
	fCreateVectorLayer,
	fCreateTDTWMTSLayer,
	fCreateTDTBaseMap,
	fInitTDTBaseMap,
	fGetLayers,
	fGetFilterLayers,
	fGetLayerProp,
	fGetLayerProps,
	fSetLayerProps,
	fIsBaseMap,
	fChangeBaseMap,
	fGetBaseMaps,
	fGetLayerByID,
	fGetLayer
}